package com.ytktt.study.week5.task10;

import com.google.common.collect.Lists;
import com.ytktt.study.week5.task10.dbms.DatabaseConnection;
import com.ytktt.study.week5.task10.entity.StudyEntity;
import com.ytktt.study.week5.task10.repository.StudyRepository;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * TODO
 *
 * @author ytk
 */
@Slf4j
public class Application {

    public static void main(String[] args) throws SQLException {
        StudyEntity studyEntity = new StudyEntity();
        studyEntity.setName("ytk");
        DatabaseConnection dc = DatabaseConnection.getInstance();
        StudyRepository repository = StudyRepository.getInstance();
        // 保存
        Connection connection1 = dc.getConnection();
        repository.save(studyEntity, connection1);
        connection1.commit();
        // 更新
        Connection connection2 = dc.getConnection();
        studyEntity.setName("ytk111");
        repository.updateById(studyEntity, connection2);
        connection2.commit();
        // 查找
        Connection connection3 = dc.getConnection();
        StudyEntity entity = repository.getById(studyEntity.getId(), connection3);
        log.info("get by id: {}", entity);
        connection3.commit();
        // 删除
        Connection connection4 = dc.getConnection();
        repository.deleteById(studyEntity.getId(), connection4);
        connection4.commit();
        // 批量
        List<StudyEntity> entities = Lists.newArrayListWithExpectedSize(100);
        for (int i = 1; i <= 100; ++i) {
            StudyEntity item = new StudyEntity();
            item.setName("batch-" + i);
            entities.add(item);
        }
        Connection connection5 = dc.getConnection();
        repository.saveBatch(entities, connection5);
        connection5.commit();

        // 事务
        try {
            StudyEntity txEntity = new StudyEntity();
            txEntity.setName("tx111");
            Connection connection6 = dc.getConnection();
            repository.save(txEntity, connection6);
            System.out.println(Integer.parseInt(txEntity.getName()));
            txEntity.setName("tx222");
            repository.updateById(txEntity, connection6);
            connection6.commit();
        } finally {
            // 关闭数据源
            dc.closeDataSource();
        }
    }
}
